package likouJava;

public class 在排序数组中查找元素的第一个和最后一个位置 {
    public int[] searchRange(int[] nums, int target) {
        int left = findLeft(nums, target);
        int right = findRight(nums,target);
        return new int[]{left, right};
    }

    private int findLeft(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        int res = -1;

        while (left <= right){
            int mid = left + (right - left) / 2;
            //向左收缩
            if (nums[mid] >= target){
                right = mid - 1;
            } else {
                left = mid + 1;
            }
            if (nums[mid] == target) res = mid;
        }
        return res;
    }

    private int findRight(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        int res = -1;

        while (left <= right) {
            int mid = left + (right - left) / 2;
            //向右收缩
            if (nums[mid] <= target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
            if (nums[mid] == target) res = mid;
        }
        return res;
    }

}
